package com.heima.wemedia.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.api.feign.ApArticleFeignClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Descriptioin DelayPublishListener
 * @Author AvA
 * @Date 2024-11-27
 */
@Component
public class DelayPublishListener {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private ApArticleFeignClient apArticleFeignClient;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue"),
            exchange = @Exchange(name = "delay.exchange", delayed = "true"),
            key = "delay.key")
    )
    public void delayMessage(String msg) {
        System.out.println("延迟交换机，收到的消息:" + msg);

        //获得文章Id
        Long wmNewsId = Long.valueOf(msg);
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        wmNews.setStatus((short) 9);

        wmNewsMapper.update(wmNews, Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,  wmNews.getId()));

        //属性赋值
        ArticleDto articleDto = new ArticleDto();
        //文章Id
        articleDto.setId(wmNews.getArticleId());
        BeanUtils.copyProperties(wmNews, articleDto);
        //作者Id
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        //布局类型
        articleDto.setLayout(wmNews.getType());
        //作者名称
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        articleDto.setAuthorName(wmUser.getName());
        //发布时间
        articleDto.setPublishTime(wmNews.getPublishTime());
        //频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());

        apArticleFeignClient.save(articleDto);

        System.out.println("success");
    }
}
